package droidhouseclone;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 *
 * @author Lorenzo Ferri
 */
public class ServerSong implements Runnable, Server {

    private int port;
    private PipedOutputStream pOut;
    private PipedInputStream pIn;
    private int maxPacketSize;
    private DatagramSocket socket;
    private Thread runReceive;

    public ServerSong(int po, int packetSize, PipedOutputStream p, PipedInputStream pi) {

        this.port = po;
        this.maxPacketSize = packetSize;
        this.pOut = p;
        this.pIn = pi;
        this.runReceive = new Thread(this);

    }

    public void startServer() {
        //Attivo il thread
        this.runReceive.start();
    }

    public void stopServer() {
        //Chiudo la socket causando la chiusura del server
        if (socket != null) {
            socket.close();
        }
    }

    public void closepipe() throws IOException {
        pIn.close();
        pOut.close();
    }

    public void run() {
        try {

            //buffer di ricezione pacchetti
            byte[] inbuf = new byte[this.maxPacketSize];
            
            //Inizializzo la socket sulla porta richiesta
            socket = new DatagramSocket(this.port);
            System.out.println("ServerSong start to port: " + this.port);
            
            //Attendo l'arrivo dei pacchetti
            while (true) {
                //inizializzo il pacchetto
                DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
                //ricezione pacchetto
                socket.receive(packet);
                //Numero di Byte ricevuti
                int numBytesReceived = packet.getLength();
                System.out.println("Received: " + numBytesReceived + " bytes...");
                //Byte ricevuto
                byte[] bytes = packet.getData();
                System.out.println("Available data in pipe: " + pIn.available() + " bytes..");
                //Inserisco i dati ricevuti nella pipe
                this.pOut.write(bytes, 0, numBytesReceived);
                this.pOut.flush();
            }


        } catch (Exception e) {
            System.out.println("ServerSong Close");
        } finally {
            stopServer();
        }
    }
}
